# -*- coding: utf-8 -*-
import frappe
from frappe.model.document import Document
from frappe.utils import flt, cint, nowdate, nowtime, get_datetime

class BatchMaterialListItem(Document):
    """
    批次领料清单子表控制器
    处理批次领料清单子表的数据验证和业务逻辑
    """
    
    def validate(self):
        """验证数据有效性"""
        self.validate_scrap_material()
        self.validate_location()
        self.validate_quantity()
        self.calculate_amount()
    
    def validate_scrap_material(self):
        """验证余料有效性"""
        if not self.scrap_material:
            frappe.throw("请选择余料")
        
        # 检查余料是否存在
        if not frappe.db.exists("Scrap Material", self.scrap_material):
            frappe.throw(f"余料 {self.scrap_material} 不存在")
        
        # 检查余料状态
        scrap_material_status = frappe.db.get_value("Scrap Material", self.scrap_material, "status")
        if scrap_material_status != "可用":
            frappe.throw(f"余料 {self.scrap_material} 状态为 {scrap_material_status}，无法添加到领料清单")
    
    def validate_location(self):
        """验证库位有效性"""
        if not self.location:
            frappe.throw("请选择库位")
        
        # 检查库位是否存在
        if not frappe.db.exists("Scrap Location", self.location):
            frappe.throw(f"库位 {self.location} 不存在")
        
        # 检查库位状态
        location_status = frappe.db.get_value("Scrap Location", self.location, "status")
        if location_status != "启用":
            frappe.throw(f"库位 {self.location} 状态为 {location_status}，无法使用")
        
        # 检查余料是否在指定库位
        if self.scrap_material:
            scrap_material_location = frappe.db.get_value("Scrap Material", self.scrap_material, "location")
            if scrap_material_location != self.location:
                frappe.throw(f"余料 {self.scrap_material} 不在库位 {self.location} 中")
    
    def validate_quantity(self):
        """验证数量"""
        if not self.quantity or flt(self.quantity) <= 0:
            frappe.throw("数量必须大于0")
        
        # 检查数量是否超过可用数量
        if self.scrap_material:
            available_quantity = frappe.db.get_value("Scrap Material", self.scrap_material, "quantity")
            if flt(self.quantity) > flt(available_quantity):
                frappe.throw(f"余料 {self.scrap_material} 数量 {self.quantity} 超过可用数量 {available_quantity}")
    
    def calculate_amount(self):
        """计算金额"""
        if self.unit_price and self.quantity:
            self.amount = flt(self.unit_price) * flt(self.quantity)
    
    def get_scrap_material_details(self):
        """获取余料详情"""
        if not self.scrap_material:
            return
        
        # 获取余料详情
        scrap_material = frappe.get_doc("Scrap Material", self.scrap_material)
        
        # 设置余料信息
        self.material_type = scrap_material.material_type
        self.material_name = scrap_material.material_name
        self.color = scrap_material.color
        self.length = scrap_material.length
        self.width = scrap_material.width
        self.thickness = scrap_material.thickness
        self.unit = scrap_material.unit
        self.location = scrap_material.location
        self.available_quantity = scrap_material.quantity
        self.unit_price = scrap_material.unit_price
        
        # 计算金额
        self.calculate_amount()
    
    def mark_as_issued(self):
        """标记为已领料"""
        self.status = "已领料"
        self.save()
        
        # 更新余料状态
        scrap_material = frappe.get_doc("Scrap Material", self.scrap_material)
        scrap_material.status = "已领料"
        scrap_material.save()
        
        # 创建领料事务记录
        self.create_issue_transaction()
        
        return True
    
    def reset_to_pending(self):
        """重置为待领料状态"""
        self.status = "待领料"
        self.save()
        
        # 更新余料状态
        scrap_material = frappe.get_doc("Scrap Material", self.scrap_material)
        scrap_material.status = "可用"
        scrap_material.save()
        
        # 创建取消领料事务记录
        self.create_cancel_issue_transaction()
        
        return True
    
    def create_issue_transaction(self):
        """创建领料事务记录"""
        # 获取父表信息
        parent_doc = frappe.get_doc("Batch Material List", self.parent)
        
        doc = frappe.new_doc("Scrap Transaction")
        doc.transaction_type = "领料"
        doc.transaction_date = parent_doc.material_date
        doc.scrap_material = self.scrap_material
        doc.warehouse = parent_doc.warehouse
        doc.location = self.location
        doc.quantity = self.quantity
        doc.reference_doctype = "Batch Material List"
        doc.reference_name = self.parent
        doc.notes = f"批次领料清单 {parent_doc.material_list_id} 领料"
        doc.insert(ignore_permissions=True)
    
    def create_cancel_issue_transaction(self):
        """创建取消领料事务记录"""
        # 获取父表信息
        parent_doc = frappe.get_doc("Batch Material List", self.parent)
        
        doc = frappe.new_doc("Scrap Transaction")
        doc.transaction_type = "取消领料"
        doc.transaction_date = nowdate()
        doc.scrap_material = self.scrap_material
        doc.warehouse = parent_doc.warehouse
        doc.location = self.location
        doc.quantity = self.quantity
        doc.reference_doctype = "Batch Material List"
        doc.reference_name = self.parent
        doc.notes = f"取消批次领料清单 {parent_doc.material_list_id} 领料"
        doc.insert(ignore_permissions=True)